//
//  CZEmoticonCollectionViewCell.swift
//  WeiBo
//
//  Created by Apple on 16/9/8.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
//  自定义表情视图cell
class CZEmoticonCollectionViewCell: UICollectionViewCell {
    //  刷新最近表情数据
    var refreshRecentEmoticon: (()->())?
    
    //  设置表情模型数组
    var emoticonsArray: [CZEmoticon]? {
        didSet {
            
            //  隐藏所有表情按钮，在绑定数据的时候让其显示
            for emoticonButton in emoticonButtonArray {
                //  默认全部隐藏
                emoticonButton.isHidden = true
            }
            
            guard let ets = emoticonsArray else {
                return
            }
            //   遍历数组赋值
            for (i, emoticon) in ets.enumerated() {
                //  表情按钮
                let button = emoticonButtonArray[i]
                button.emoticon = emoticon
                //  代码抽取到emoticon里面
//                button.isHidden = false
//                //  判断type 0 -> 图片，1 —> emoji
//                if emoticon.type == "0" {
//                    //  图片全路径
//                    button.setImage(UIImage(named: emoticon.path!), for: .normal)
//                    //  文本该为空
//                    button.setTitle(nil, for: .normal)
//                } else {
//                    //  emoji
//                    button.setTitle((emoticon.code! as NSString).emoji(), for: .normal)
//                    //  图片改完空
//                    button.setImage(nil, for: .normal)
//                }
                
                
            }
        }
    }
    
    
    //  记录20个表情按钮
    fileprivate lazy var emoticonButtonArray: [CZEmoticonButton] = [CZEmoticonButton]()
    
    //  绑定数据
    var indexPath: IndexPath? {
        didSet {
            guard let index = indexPath else {
                return
            }
            
            messageLabel.text = "当前显示的是第\(index.section + 1)组第\(index.item + 1)页"
        }
    }
    
    // MARK:    --懒加载控件
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 20)
        label.textColor = UIColor.brown
        return label
        
    }()
    
    //  删除表情按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete"), for: .normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), for: .highlighted)
        
        return button
    }()
    
    //  长按popView
    private lazy var longPressPopView: CZEmoticonPopView = CZEmoticonPopView.emoticonPopView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        //  给contentview添加长按手势
        let longGestureRec = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:)))
        contentView.addGestureRecognizer(longGestureRec)
        
        //  添加表情按钮
        addChildButton()
        
//        contentView.addSubview(messageLabel)
//        messageLabel.snp_makeConstraints { (make) in
//            make.center.equalTo(contentView)
//        }
        //  添加删除按钮
        contentView.addSubview(deleteButton)
        
    }
    
    //  添加20个表情按钮
    private func addChildButton() {
        for _ in 0..<20 {
            let button = CZEmoticonButton()
            //  点击表情按钮事件
            button.addTarget(self, action: #selector(emoticonButtonAction(button:)), for: .touchUpInside)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 34)
            //  添加按钮
            contentView.addSubview(button)
            //  添加当前的按钮到指定的数组中
            emoticonButtonArray.append(button)
        }
    
    }
    
    //  长按手势
    @objc private func longPressAction(gesture: UIGestureRecognizer) {
        
        
        
        let window = UIApplication.shared.windows.last!
        //  获取点击的点
        let currentPoint = gesture.location(in: contentView)
        //  当前点击的表情按钮
        var currentEmoticonButton: CZEmoticonButton?
        //  循环遍历表情按钮查找长按的position是否在按钮的frame范围内
        for emoticonButton  in emoticonButtonArray {
            //  判断点是否在其frame的范围内
            if emoticonButton.frame.contains(currentPoint)  {
                currentEmoticonButton = emoticonButton
                break
            }
            
        }
        //  没有找到则返回
        guard let emoticonButton = currentEmoticonButton else {
            return
        }
        
        //  完成坐标转换
        let convertRect = emoticonButton.convert(emoticonButton.bounds, to: window)
        
        //  设置popView的位置
        longPressPopView.y = convertRect.maxY - longPressPopView.height
        longPressPopView.centerX = convertRect.midX
        
        //  绑定数据
        longPressPopView.emotionButton.emoticon = emoticonButton.emoticon
        
        //  判断手势
        switch gesture.state {
        case .began, .changed:
            // 移动, addSubview的含义 移除原有的在添加新的视图
            window.addSubview(longPressPopView)
            
        print("移动")
        case .ended:
            print("移除屏幕外或者来电话")
            longPressPopView.removeFromSuperview()
            
            //  再通过点击的位置查找
            let location = gesture.location(in: contentView)
            
            
            var tempEmoticonButton: CZEmoticonButton?
            //  循环遍历表情按钮查找长按的position是否在按钮的frame范围内
            for emoticonButton  in emoticonButtonArray {
                //  判断点是否在其frame的范围内
                if emoticonButton.frame.contains(location)  {
                    tempEmoticonButton = emoticonButton
                    break
                }
                
            }
            
            
            if let emoticonButton = tempEmoticonButton {
                //  发送通知
                NotificationCenter.default.post(name: NSNotification.Name(DidSelectedEmoticonNotification), object: emoticonButton.emoticon!)
            }
            
            
            
            
        default:
            print("删除pop视图")
            longPressPopView.removeFromSuperview()
        }
    }
    
    
    // MARK:    --点击表情按钮事件
    @objc private func emoticonButtonAction(button: CZEmoticonButton) {
        
        
        //  发送通知方式让撰写控制器得到点击的表情模型
        NotificationCenter.default.post(name: NSNotification.Name(DidSelectedEmoticonNotification), object: button.emoticon!)
        
        //  归档数据
        DispatchQueue.global().async {
            //  归档数据
            CZEmoticonTools.shareTools.saveRecentEmoticon(emoticon: button.emoticon!)
        }
        
        
        
        let popView = CZEmoticonPopView.emoticonPopView()
        //  绑定数据
        popView.emotionButton.emoticon = button.emoticon
        //  添加到contentView上不行，因为上面的toolbar条会挡住
//        contentView.addSubview(popView)
        //  添加到最上层window上
        let window = UIApplication.shared.windows.last!
        window.addSubview(popView)
        
        //  将当前点击的视图的rect转换到window上
        let convertRect = button.convert(button.bounds, to: window)
        
        //  设置中心点
        popView.y = convertRect.maxY - popView.height
        popView.centerX = convertRect.midX
        
        //  延迟0.3秒移除掉
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            popView.removeFromSuperview()
        }
        
        
        //  刷新最近数据
        refreshRecentEmoticon?()
    }
    
    
    //  子控件布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        
        //  每项的宽度
        let itemWidth = width / 7
        //  每项的高度
        let itemHeight = height / 3
        
        
        //  变量表情按钮
        for (i, value) in emoticonButtonArray.enumerated() {
            value.size = CGSize(width: itemWidth, height: itemHeight)
            //  计算当前列数索引
            let colIndex = i % 7
            //  计算当前行数索引
            let rowIndex = i / 7
            
            value.x = CGFloat(colIndex) * itemWidth
            value.y = CGFloat(rowIndex) * itemHeight
        
        }
        
        //  删除按钮的frame
        deleteButton.size = CGSize(width: itemWidth, height: itemHeight)
        deleteButton.x = width - itemWidth
        deleteButton.y = height - itemHeight
    }
}
